<script setup lang="ts">
  import { loginByPasswordApi } from '@/apis/user'
  import { useUserStore } from '@/stores/user'
  import { ref } from 'vue'

  defineOptions({
    options: {
      styleIsolation: 'shared',
    },
  })

  const loginbypassword = async () => {}

  const biaoData = ref({
    mobile: '13230000076',
    password: 'abc12345',
  })

  const formrules: UniHelper.UniFormsRules = {
    mobile: {
      rules: [
        { required: true, errorMessage: '手机号不能为空' },
        { pattern: '^1[0-9]{10}$', errorMessage: '手机号格式不正确' },
      ],
    },
    password: {
      rules: [
        { required: true, errorMessage: '密码不能为空' },
      ],
    },
  }

  const form = ref<UniHelper.UniFormsInstance>()

  const isArgee = ref(false)

  const onSubmit = async () => {
    try {
      await form.value?.validate?.()

      // 判断是否同意用户协议
      if (!isArgee.value) {
        return uni.showToast({ title: '请先同意用户协议和隐私协议', icon: 'none' })
      }

      const res = await loginByPasswordApi(biaoData.value)
      // 保存 token 到 store 中，store 已开启持久化
      const store = useUserStore()
      store.setToken(res.token)
      // 成功提示
      uni.showToast({ title: '登录成功', icon: 'success' })
      // 登录成功，跳转首页，注意：这里需要用 switchTab
      uni.switchTab({ url: '/pages/index/index' })
    } catch (err) {
      console.log(err)
    }
  }
</script>

<template>
  <uni-forms class="login-form" ref="form" :model="biaoData" :rules="formrules">
    <uni-forms-item name="mobile">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
        v-model="biaoData.mobile"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <uni-easyinput
        type="password"
        placeholder="请输入密码"
        :input-border="false"
        placeholder-style="color: #C3C3C5"
        v-model="biaoData.password"
      />
    </uni-forms-item>
    <view class="agreement">
      <radio :checked="isArgee" @click="isArgee = !isArgee" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="onSubmit()" >登 录</button>
    <navigator hover-class="none" class="uni-navigator" url=" "> 忘记密码？ </navigator>
  </uni-forms>
</template>

<style lang="scss">
  @import './style.scss';
</style>
